package com.tzbank.utils;


import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class AppUtils {
	private static Logger logger = LoggerFactory.getLogger(AppUtils.class);
	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	/**
	 * Base64加密
	 * @author jlchen4
	 * @date 2017年9月16日 下午3:45:30
	 * @param str	加密字符串
	 * @return
	 */
	public static String getBase64(String str) {
		if (str == null || "".equals(str)) {
			return "";
		}
		try {
			byte[] encodeBase64 = Base64.encodeBase64(str.getBytes("UTF-8"));
			str = new String(encodeBase64);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}

	/**
	 * md5加密
	 * @author jlchen4
	 * @date 2017年9月16日 下午3:44:46
	 * @param source	加密字符串
	 * @return
	 */
	public static String md5Encode(String source) {
		String result = null;
		try {
			result = source;
			// 获得MD5摘要对象
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			// 使用指定的字节数组更新摘要信息
			messageDigest.update(result.getBytes("utf-8"));
			// messageDigest.digest()获得16位长度
			result = byteArrayToHexString(messageDigest.digest());
		} catch (Exception e) {
			logger.error("Md5 Exception!", e);
		}
		return result;
	}

	private static String byteArrayToHexString(byte[] bytes) {
		StringBuilder stringBuilder = new StringBuilder();
		for (byte tem : bytes) {
			stringBuilder.append(byteToHexString(tem));
		}
		return stringBuilder.toString();
	}

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}



	/**
	 *
	 * @return

	public static String JsonToString(String json) {
	JSONObject jsonObject = new JSONObject(json);
	String Metainfo=jsonObject.toString();
	return Metainfo;
	}
	 */
	/**
	 * 接入方请求的唯一标识，由字母、数字、下划线组成，商户须确保其唯一性。
	 * （建议：开头使用一段自定义商户简称，中间使用一段日期，末尾使用一个序列）
	 * @return
	 */
	public static String getbizId() {
		String tzb="TZBANK";
		String time = DateUtils.dateToDateFullString(new Date());
		String uuid = UUID.randomUUID().toString().replace("-", "").substring(10, 20);
		String bizId = tzb+"-"+uuid+"-"+time;
		return bizId;
	}

	/**
	 * 公钥
	 */
	private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxav0oL0tJJf1KxiM1rDBChK/ANM7yWkA/sjhZwfZRjPpbGuMLN2HDtfyyYKtj5jg8AggarvofiVmC0omyWiiZUeZ+z9pjH+SxgFbrf6rHPNNkg7Q6S8WgBUOMK+nyus3u2U7YkxJgk/qtGNM72VP8x2TJgGavZfxH1rfFdf041qVGxSSZBgtU+ic5TX31XbIeKCd+BBy+AZiBTnqE19rbSfqNebHRAQzOfwUBiMbvmnQ4FagH6cqLPyH+NMQm5fWHPkCdgNgf8sp+5Du7kgmUkLljxz2Zqg3fQlYSrCjSrmQs2brIuoMTeC91wWNjxyS56vcLRAjMUZsIGqPNHlScwIDAQAB";

	public static String toRSA(Map<String, String> map) {

		/**
		 * 用户信息
		 */
/*        Map<String, String> identityParam = new HashMap<String, String>();
        identityParam.put("identityType", "CERT");//保持不变
        identityParam.put("certType", "IDCARD");//保持不变
        identityParam.put("certName", "汪达俊");//用户姓名
        identityParam.put("certNo", "340521199311142312");//用户身份证号
*/
		byte[] publicKeyDecode = Base64.decodeBase64(publicKey);
		byte[] rsaCryptoBytes = null;
		try {
			/**
			 * RSA加密
			 */
			rsaCryptoBytes = RSACryptoUtil.rsaCrypto((JSON.toJSONString(map)).getBytes("UTF-8"),
					publicKeyDecode, "RSA", Cipher.ENCRYPT_MODE);

		} catch (UnsupportedEncodingException e) {
			System.out.println("转码异常:" + e);
		} catch (GeneralSecurityException e) {
			System.out.println("加密异常:" + e);
		}
		String identityParamEncrypt = "";
		if(rsaCryptoBytes != null){
			identityParamEncrypt = Base64.encodeBase64URLSafeString(rsaCryptoBytes);
		}
		//  System.out.println("最终得到字符串identityParamEncrypt:" + identityParamEncrypt);

		return identityParamEncrypt;
	}
}
